package com.goodboys.controller;

import com.alibaba.fastjson.JSON;
import com.goodboys.base.controller.BaseController;
import com.goodboys.base.entity.BaseReqBean;
import com.goodboys.base.resp.Response;
import com.goodboys.base.webscoket.SocketSessionRegistry;
import com.goodboys.entity.Info;
import com.goodboys.entity.LngLat;
import com.goodboys.entity.User;
import com.goodboys.service.InfoService;
import com.goodboys.service.UserService;
import com.goodboys.utils.BaiduLocationUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by CJ on 2018-05-19.
 */
@RestController
@RequestMapping("/info")
public class InfoController extends BaseController<Info>{

    private final Logger logger = LoggerFactory.getLogger(InfoController.class);

    @Autowired
    private InfoService infoService;
    /**session操作类*/
    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;
    /**消息发送工具*/
    @Autowired
    private SimpMessagingTemplate template;
    /**
     * 查询指定用户的发布信息列表(根据用户id)
     * @param baseReqBean
     * @return
     */
    @GetMapping("/infoList")
    @ResponseBody
    public Response userInfoList(BaseReqBean baseReqBean){
        Response response = new Response();
        try {
            Map result = infoService.infos(baseReqBean);
            return getRetunPageList(result,response);
        } catch (Exception e) {
            logger.error("查询用户发布信息失败。。。");
            e.printStackTrace();
            return response.failure("查询用户发布信息失败，请重试。。。");
        }
    }

    @PostMapping("/publish")
    @ResponseBody
    public Response publish(BaseReqBean baseReqBean){
        Response response = new Response();
        try {
            Map map = infoService.publish(baseReqBean);
            //发送至目标用户
            if((Integer)map.get("status")==1 && map.get("message") instanceof Info) {
                Info message = (Info)map.get("message");
                String content = message.getContent();
                String title = message.getTitle();
                webAgentSessionRegistry.getAllSessionIds().entrySet().stream()
                        .map(Map.Entry::getValue).flatMap(users -> users.stream().collect(Collectors.toList()).stream())
//                        .filter(user -> baseReqBean.getId().equals(user.getId()))
//                        .filter(user -> user.getType() == baseReqBean.getType())
//                        .filter(user -> user.getTag() == null || user.getTag() == baseReqBean.getTag())
//                        .filter(user -> user.getRange() <= BaiduLocationUtils.getDistance(new LngLat(user.getLat(), user.getLng()),
//                                new LngLat(baseReqBean.getLat(), baseReqBean.getLng())))
//                        .filter(user -> (StringUtils.isEmpty(user.getKeyword()) || content.contains(user.getKeyword())
//                                || title.contains(user.getKeyword())))
                        .forEach(user -> {
                            template.convertAndSendToUser(user.getSessionId(),"/topic/publish",
                                JSON.toJSONString(map),createHeaders(user.getSessionId()));
                            System.out.println(user.getId());});
            }
            return getRetunResult(map, new Response());
        } catch (Exception e) {
            logger.error("信息发布失败。。。");e.printStackTrace();
            return response.failure("信息发布失败，请重试。。。");
        }
    }



}
